package jp.ac.nitech.matlab.najm.server;

import java.io.OutputStream;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.File;

import jp.ac.nitech.matlab.najm.net.Protocol;


public class Response {

  private static final int BUFFER_SIZE = 1024;
  
  
  Handler request;
  OutputStream output;

  public Response(OutputStream output) {
    this.output = output;
  }

  public void setRequest(Handler request) {
    this.request = request;
  }
  
  public void sendOK(){
	  
  }

  public void sendStaticResource(File file) throws IOException {
    byte[] bytes = new byte[BUFFER_SIZE];
    FileInputStream fis = null;
    try {
      //File file = new File(Setting.getInstance().getSetting("documentRoot"), request.getUri());
      if (file.exists()) {
        fis = new FileInputStream(file);
        int ch = fis.read(bytes, 0, BUFFER_SIZE);
        while (ch!=-1) {
          output.write(bytes, 0, ch);
          ch = fis.read(bytes, 0, BUFFER_SIZE);
        }
      }
      else {
        // file not found
        String errorMessage = Protocol.RES_ERR;
        output.write(errorMessage.getBytes());
      }
    }
    catch (Exception e) {
      // thrown if cannot instantiate a File object
      System.out.println(e.toString() );
    }
    finally {
      if (fis!=null)
        fis.close();
    }
  }
}